frames reset
clear all 


use "temp\sampledata.dta", clear 
levelsof year, local(years)

foreach y of local years {
	di "Year: `y'"
	
		foreach v in agecat male educ district { 
	
			qui use "popdata/targets/`v'_1983-2021.dta", clear
			qui keep if year==`y'

			qui expand n
			qui svyset [weight=xswt]

			qui version 14: svy: total _one, over(`v', nolab)
			qui matrix t_`v'_`y' = e(b)
			qui matrix rownames t_`v'_`y' = `v'
			qui mat t_`v'_`y' = t_`v'_`y' / _N 
			}

		qui use temp/sampledata.dta, clear

		qui keep if year==`y' & fresh==1
		
		qui drop if mi(district) | mi(male) | mi(agecat)

		qui clonevar w_xswt = xswt 
		gen _one= 1
		
		foreach v in agecat male educ district  {	
				cap qui mat t_`v'_`y'_N = t_`v'_`y' * _N
			}
				

		foreach h in 5 {
			di "       - Trimming: `h'"
			* Age only	

			qui ipfraking [pw=xswt], ///
					ctotal(t_agecat_`y'_N) generate(w_A_`h') trimhiabs(`h') nograph
			* District only	
			qui ipfraking [pw=xswt], ///
					ctotal(t_district_`y'_N) generate(w_D_`h') trimhiabs(`h') nograph
			* Age, gender, district 
			qui ipfraking [pw=xswt] if inrange(party,1,89), ///
					ctotal(t_agecat_`y'_N t_male_`y'_N t_district_`y'_N) ///
					generate(w_AMD_`h') trimhiabs(`h') nograph
			* Educ only
			qui ipfraking [pw=xswt] if !mi(educ), ///
					ctotal(t_educ_`y'_N) generate(w_E_`h') trimhiabs(`h') nograph
			* Age, gender, district, educ 
			qui ipfraking [pw=xswt] if inrange(party,1,89) & !mi(educ), ///
					ctotal(t_agecat_`y'_N t_male_`y'_N t_district_`y'_N t_educ_`y'_N) ///
					generate(w_AMDE_`h') trimhiabs(`h') nograph				
			qui save "temp/weights_`y'.dta", replace
		}
}
		

use "temp\sampledata.dta", clear 
		
levelsof year, local(years)

foreach y of local years {
	di "Year: `y'"
		merge 1:1 pid using "temp/weights_`y'.dta", keepus(w*) update nogen
}

save "data/icenes8321_weights", replace

